import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { title: '注册', requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/layouts/MainLayout.vue'),
    redirect: '/home',
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('@/views/Dashboard.vue'),
        meta: { 
          title: '首页', 
          requiresAuth: true,
          roles: ['SUPER_ADMIN', 'ADMIN', 'USER'] // 所有角色都可访问
        }
      },
      {
        path: 'categories',
        name: 'Categories',
        component: () => import('@/views/categories/index.vue'),
        meta: { 
          title: '分类管理', 
          requiresAuth: true,
          roles: ['SUPER_ADMIN', 'ADMIN', 'USER'] // 所有角色都可访问，但操作权限不同
        }
      },
      {
        path: 'products',
        name: 'Products',
        component: () => import('@/views/products/index.vue'),
        meta: { 
          title: '商品管理', 
          requiresAuth: true,
          roles: ['SUPER_ADMIN', 'ADMIN', 'USER'] // 所有角色都可访问，但操作权限不同
        }
      },
      {
        path: 'orders',
        name: 'Orders',
        component: () => import('@/views/orders/index.vue'),
        meta: { 
          title: '订单管理', 
          requiresAuth: true,
          roles: ['SUPER_ADMIN', 'ADMIN', 'USER'] // 所有角色都可访问，但操作权限不同
        }
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('@/views/users/index.vue'),
        meta: { 
          title: '用户管理', 
          requiresAuth: true,
          roles: ['SUPER_ADMIN', 'ADMIN'] // 只有超级管理员和管理员可访问
        }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/404.vue'),
    meta: { title: '页面不存在' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 商城管理系统` : '商城管理系统'
  
  const userStore = useUserStore()
  const token = userStore.token
  
  console.log('路由跳转:', to)
  console.log('Token状态:', token)

  // 如果需要登录权限
  if (to.meta.requiresAuth) {
    if (!token) {
      // 未登录，重定向到登录页
      next({ 
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    }

    // 已登录但没有用户信息，获取用户信息
    if (!userStore.username) {
      try {
        await userStore.getInfo()
      } catch (error) {
        // 获取用户信息失败，清除 token 并重定向到登录页
        userStore.resetToken()
        next({ 
          path: '/login',
          query: { redirect: to.fullPath }
        })
        return
      }
    }
    
    // 检查用户角色权限
    const { roles } = to.meta
    if (roles && roles.length > 0) {
      const hasPermission = roles.includes(userStore.role)
      if (!hasPermission) {
        ElMessage.warning(`您没有权限访问${to.meta.title}`)
        next({ path: '/home' })
        return
      }
    }
  }

  // 已登录用户访问登录页，重定向到首页
  if (to.path === '/login' && token) {
    next({ path: '/' })
    return
  }

  next()
})

export default router 